#include "kdctextcodeccombobox.h"

#include <QString>
#include <QStringList>
#include <QTextCodec>

#include <KGlobal>
#include <KCharsets>
#include <KLocale>

KDCTextCodecComboBox::KDCTextCodecComboBox( QWidget *parent ) : KComboBox( parent )
{
	QString sEncoding = QString();
	QString systemEncoding = QLatin1String( KGlobal::locale()->encoding() );
	if ( sEncoding.isEmpty() )
		sEncoding = systemEncoding;

	QStringList encodings( KGlobal::charsets()->availableEncodingNames() );
	int insert = 0;
	int system = 0;
	bool foundRequested = false;
	for ( int i = 0; i<encodings.count(); i++ )
	{
		bool found = false;
		QTextCodec *codecForEnc = KGlobal::charsets()->codecForName( encodings[i], found );
		if ( found )
		{
			addItem( encodings[i] );
			if ( ( codecForEnc->name() == sEncoding ) || ( encodings[i] == sEncoding ) )
			{
				setCurrentIndex( insert );
				foundRequested = true;
			}
			if ( ( codecForEnc->name() == systemEncoding ) || ( encodings[i] == systemEncoding ) )
				system = insert;
			insert++;
		}
	}

	if ( !foundRequested )
		setCurrentIndex( system );

	setCurrentItem( sEncoding );
	connect( this, SIGNAL( currentIndexChanged( int ) ), this, SLOT( on_currentIndexChanged( int ) ) );
}

KDCTextCodecComboBox::~KDCTextCodecComboBox()
{

}

QString KDCTextCodecComboBox::currentCodec() const
{
	return currentText();
}

void KDCTextCodecComboBox::setCurrentCodec( const QString& codec )
{
	setCurrentItem( codec );
}

void KDCTextCodecComboBox::on_currentIndexChanged( int )
{
	emit currentCodecChanged( currentCodec() );
}
